import React, { ReactElement, useMemo } from 'react';
import { Form, FormInstance } from 'antd';
import EditableContext from './editableContext';
import { SortableElement } from 'react-sortable-hoc';

interface EditableRowProps {
  'data-row-key': string;
  children: any;
}
export type IformRef = FormInstance & {
  refs: { [key: string]: any };
  startEdit: () => void;
  endEdit: () => void;
};
const SortableItem = SortableElement((props: object) => <tr {...props} />);
const validateMessages = {
  required: '此字段不能为空',
};

const EditableRow =
  (dataSource: object[], rowKey: string, formRef: IformRef) =>
  (props: EditableRowProps): ReactElement => {
    const [form] = Form.useForm();
    const index = dataSource.findIndex(
      (x) => x[rowKey] === props['data-row-key'],
    );
    const { children, ...other } = props;
    useMemo(() => {
      if (!formRef[props['data-row-key']]) {
        formRef[props['data-row-key']] = {};
      }
      Object.assign(formRef[props['data-row-key']], {
        ...form,
        refs: {},
        startEdit: function () {
          Object.values(this.refs).forEach((ref) => {
            //@ts-ignore
            ref?.current?.startEdit?.();
          });
        },
        endEdit: function () {
          Object.values(this.refs).forEach((ref) => {
            //@ts-ignore
            ref?.current?.endEdit?.();
          });
        },
      });
    }, []);

    return (
      <SortableItem index={index} {...other}>
        <Form form={form} component={false} validateMessages={validateMessages}>
          <EditableContext.Provider
            value={{ form, refs: formRef[props['data-row-key']]?.refs }}
          >
            {children}
          </EditableContext.Provider>
        </Form>
      </SortableItem>
    );
  };

export default EditableRow;

export { validateMessages };
